<?php
/**
 * @Desc:  后台登录控制器
 * @Author: hpp
 * @Date:   2018-11-08 10:49:39
 * @Last Modified by:   hpp
 * @Last Modified time: 2018-11-08 12:53:26
 */
namespace app\admin\controller;

use think\Controller;
use think\Request;
use think\captcha\Captcha;
use app\admin\model\Admin;
use app\admin\model\AdminRole;
use app\admin\model\Role;
use app\admin\model\LoginLog;

class Login extends Controller
{
	public function login()
	{
		if(session('user')){
			return redirect('/admin');
		}
		return $this->fetch();
	}

	public function doLogin()
	{
		$data = input('post.');
		if(!$data['email']) return $this->error('邮箱不能为空',null,'email');
		$pattern = "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/";
		if(!preg_match($pattern,$data['email'])){
			return $this->error('邮箱格式不正确',null,'email');
		}
		if(!$data['password']) return $this->error('密码不能为空',null,'password');
		if(!captcha_check($data['code'])) return $this->error('验证码不正确',null,'code');

		$admin = Admin::where(['email' => $data['email']])->find();

		if($admin['status'] == 0) return $this->error('已被禁用，请联系管理员');
		if(!$admin) return $this->error('邮箱不存在');
		$password = md5_password($data['password']);
		if($admin['password'] !== $password){
			return $this->error('密码不正确',null,'password');
		}
		session('user',$admin);
		$roleId = AdminRole::where('admin_id',$admin['id'])->value('role_id');
		$roleName = Role::where('id',$roleId)->value('name');
		session('role_name',$roleName);

		// 添加登录日志
		$loginLogId = LoginLog::saveLoginLog($admin['id']);
		session('login_log_id',$loginLogId);

		return $this->success('登录成功',url('/admin'));
	}

	public function logout()
	{
		$id = session('login_log_id');
		if($id){
			LoginLog::where('id',$id)->update(['last_login_time' => date('Y-m-d H:i:s',time())]);
		}
		session('user',null);
		session(null);
		return redirect('/admin/login');
	}

	public function wxlogin(){
		header("Content-type: text/html; charset=utf-8");
		$redirect_uri="http://39.104.173.6/wx";
		$redirect_uri=urlencode($redirect_uri);
		$appID="wxca95ea530559a98e";
		$scope="snsapi_login";
		$url = "https://open.weixin.qq.com/connect/qrconnect?appid=" . $appID."&redirect_uri=".$redirect_uri
			."&response_type=code&scope=".$scope."&state=STATE#wechat_redirect";
		$result = file_get_contents($url);dump($url);die;
		$result = str_replace("/connect/qrcode/", "https://open.weixin.qq.com/connect/qrcode/", $result);
		return $result; //返回页面
	}

	public function wx(){

	}

	public function verify(){
		$captcha = new Captcha();
		$captcha->fontSize = 20;
		$captcha->useCurve = false;
		$captcha->length = 4;
		return $captcha->entry();
	}
}